package com.ruoyi.web.controller.kaoyan;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.kaoyan.domain.*;
import com.ruoyi.kaoyan.service.EducationCategoryService;
import com.ruoyi.kaoyan.service.EducationChoicePlanService;
import com.ruoyi.kaoyan.service.EducationFileInfoService;
import com.ruoyi.system.domain.SysFileInfo;
import com.ruoyi.system.service.ISysFileInfoService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 前台资料分享类
 * @author carpediem
 */
@Api(tags = "前台考研资料管理", value = "前台考研资料管理")
@RestController
@RequestMapping("/v2/file")
public class FileApi extends BaseController {

    @Autowired
    private EducationFileInfoService educationFileInfoService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysFileInfoService fileInfoService;
    @Autowired
    private EducationCategoryService categoryService;

    @Autowired
    private EducationChoicePlanService planService;

    @ApiOperation("考研资料列表")
    @PostMapping("/list")
    public AjaxResult list(Long userId, String title, String majorName, String schoolName){
        LambdaQueryWrapper<EducationFileInfo> queryWrapper = new LambdaQueryWrapper<EducationFileInfo>()
                .like(StringUtils.isNotBlank(title), EducationFileInfo::getName, title)
                .like(StringUtils.isNotBlank(majorName), EducationFileInfo::getMajorName, majorName)
                .like(StringUtils.isNotBlank(schoolName), EducationFileInfo::getSchoolName, schoolName)
                .eq(EducationFileInfo::getVerFlag, 1);
        if (StringUtils.isNotNull(userId)){
            queryWrapper.eq(EducationFileInfo::getUserId, userId);
        }
        Page<EducationFileInfo> page = educationFileInfoService.page(startPagePlus(), queryWrapper);
        List<EducationFileInfo> records = page.getRecords();
        Set<String> fileIdSet = records.stream().map(EducationFileInfo::getFileGroupId).collect(Collectors.toSet());
        Set<Long> categoryIdSet = records.stream().map(EducationFileInfo::getCategoryId).collect(Collectors.toSet());
        //用户名
        List<Long> userIdSet = records.stream().map(EducationFileInfo::getUserId).collect(Collectors.toList());
        List<SysUser> userList = userService.list(new LambdaQueryWrapper<SysUser>()
                .in(StringUtils.isNotEmpty(userIdSet), SysUser::getUserId, userIdSet));
        Map<Long, String> userNameMap = userList.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getUserName));
        //类目名
        List<EducationCategory> categories = categoryService.list(new LambdaQueryWrapper<EducationCategory>()
                .in(StringUtils.isNotEmpty(categoryIdSet), EducationCategory::getId, categoryIdSet));
        Map<Long, String> categoryMap = categories.stream().collect(Collectors.toMap(EducationCategory::getId, EducationCategory::getName));
        //文件地址
        Map<String, List<SysFileInfo>> filePathMapList = fileInfoService.getFilePathMapList(fileIdSet);
        records.forEach(e -> {
            e.setUserName(userNameMap.get(e.getUserId()));
            e.setCategoryName(categoryMap.get(e.getCategoryId()));
            e.setFileInfoList(filePathMapList.get(e.getFileGroupId()));
        });
        return AjaxResult.ok().page(page, records).build();
    }

    @ApiOperation("上传资料或修改资料信息")
    @PostMapping("/saveOrUpdate")
    public AjaxResult saveOrUpdate(@RequestBody EducationFileInfo fileInfo){
        if (StringUtils.checkObjAllFieldsIsNull(fileInfo)){
            return AjaxResult.warn("内容为空");
        }
        Long userId = SecurityUtils.getUserId();
        if (StringUtils.isNull(userId)){
            return AjaxResult.warn("请重新登陆");
        }
        EducationChoicePlan choicePlan = new EducationChoicePlan();
        choicePlan.setTargetMajorName("未知专业");
        choicePlan.setTargetSchoolName("未知学校");
        EducationChoicePlan plan = Optional.ofNullable(planService.getOne(new LambdaQueryWrapper<EducationChoicePlan>()
                .eq(EducationChoicePlan::getUserId, userId).last("limit 1"))).orElse(choicePlan);
        String targetMajorName = plan.getTargetMajorName();
        String targetSchoolName = plan.getTargetSchoolName();
        fileInfo.setMajorName(Optional.ofNullable(targetMajorName).orElse(""));
        fileInfo.setSchoolName(Optional.ofNullable(targetSchoolName).orElse(""));
        boolean saveOrUpdate = educationFileInfoService.saveOrUpdate(fileInfo);
        return toAjax(saveOrUpdate);
    }

    @ApiOperation("移除资料")
    @PostMapping("/remove")
    public AjaxResult deleteFile(Long id){
        boolean remove = educationFileInfoService.removeById(id);
        return toAjax(remove);
    }

}
